package com.cy.aircompressor.main.welcome;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.lifecycle.Observer;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.FragmentLoginBinding;
import com.cy.aircompressor.db.DemoDbHelper;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.MainActivity;
import com.cy.aircompressor.main.welcome.viewmodel.WelcomeViewModel;
import com.cy.aircompressor.utils.UsageUtil;
import com.drug.lib.util.DLog;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.net.model.base.Resource;
import com.net.model.base.activity.BaseVMActivity;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;

/**
 * 版权：周和权 版权所有
 *
 * @author zhouhequan
 * 版本：1.0
 * 创建日期：2023/4/4 or 14:17
 * 描述：进入app第一个展示页面
 */
public class LoginActivity extends BaseVMActivity<FragmentLoginBinding, WelcomeViewModel> {
    public static void start(Context activity) {
        Intent intent = new Intent();
        intent.setClass(activity, LoginActivity.class);
        activity.startActivity(intent);
    }

    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected FragmentLoginBinding getViewBinding() {
        return FragmentLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        DemoDbHelper.getInstance().initDb();
        DemoDbHelper.getInstance().getDatabaseCreatedObservable().observe(this, aBoolean -> {
            DLog.i("本地数据库初始化完成");
        });
        Observable<CharSequence> name_observable = RxTextView.textChanges(mBinding.etUsername);
        Observable<CharSequence> pwd_observable = RxTextView.textChanges(mBinding.etPassword);
        Observable.combineLatest(name_observable, pwd_observable, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @NonNull
            @Override
            public Boolean apply(@NonNull CharSequence charSequence, @NonNull CharSequence charSequence2) throws Exception {
                return !TextUtils.isEmpty(charSequence) && !TextUtils.isEmpty(charSequence2);
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                mBinding.btnLogin.setEnabled(aBoolean);
            }
        });

        RxView.clicks(mBinding.btnLogin)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe((o -> {
                    String name = mBinding.etUsername.getText().toString();
                    String pwd = mBinding.etPassword.getText().toString();
                    SPManager.putLoginInfo(name, pwd);
                    mViewModel.login(name, pwd);
                }));

        if (!TextUtils.isEmpty(SPManager.getUserName())) {
            mBinding.etUsername.setText(SPManager.getUserName());
        }
//        if (!TextUtils.isEmpty(SPManager.getPassWord())) {
//            mBinding.etPassword.setText(SPManager.getPassWord());
//        }
        mBinding.rememberPassword.setChecked(SPManager.getRememberPassword());
        XXPermissions.with(this).permission(REQUESTED_PERMISSIONS).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {

            }
        });

        RxCompoundButton.checkedChanges(mBinding.rememberPassword).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                SPManager.putRememberPassword(aBoolean.booleanValue());
            }
        });
        UsageUtil.hasPermissionToReadNetworkStats(mContext);
    }

    @Override
    protected void dataChange() {
        mViewModel.getLoginObservable().observe(this, boserver -> {
            boserver.handler(new OnCallback<String>(true, false) {
                @Override
                public void onSuccess(String data) {
                    SPManager.setToken(data);
                    AirConfig.get().updateLoginFlag(true);
                    mViewModel.currentUserInfo();


                }

                @Override
                public void onFailure(Integer code, String message) {
                    super.onFailure(code, message);
                    ToastUtil.show(message);
                }
            });
        });

        mViewModel.getUserInfoObservable().observe(this, new Observer<Resource<UserInfo>>() {
            @Override
            public void onChanged(Resource<UserInfo> userInfoResource) {
                userInfoResource.handler(new OnCallback<UserInfo>(false, true) {
                    @Override
                    public void onSuccess(UserInfo data) {
                        AirConfig.get().updateUserInfo(data);

                        MainActivity.start(LoginActivity.this);
                        finish();
                    }

                });
            }
        });
    }
}
